package com.centriole.common.log;

import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.centriole.common.component.EurekaClientUtils;

import java.io.IOException;
import java.util.concurrent.FutureTask;

/**
 *  功   能：日志工具类
 *  创建人：陈默晗
 *  时   间：2018年3月22日下午3:40:18
 */
@Component
public class LogUtils {

    /**
     * 注册Eureka使用的服务id
     */
    public static String SERVICE_ID;

    /**
     * info日志
     * @param msg   日志信息
     * @return  true表示记录日志成功；否则false
     */
    public static FutureTask<Boolean> info(String msg){
        return log("INFO",msg);
    }

    /**
     * error日志
     * @param msg   日志信息
     * @return  true表示记录日志成功；否则false
     */
    public static FutureTask<Boolean> error(String msg){
        return log("ERROR",msg);
    }

    /**
     * debug日志
     * @param msg   日志信息
     * @return  true表示记录日志成功；否则false
     */
    public static FutureTask<Boolean> debug(String msg){
        return log("DEBUG",msg);
    }

    /**
     * 使用okHttp进行远程服务调用
     * @param level    日志等级(DEBUG、INFO、ERROR)
     * @param msg   日志信息
     * @return  true表示记录日志成功；否则false
     */
    private static FutureTask<Boolean> log(String level,String msg){

        FutureTask<Boolean> async = new FutureTask<>(()->{
            String url = EurekaClientUtils.getServiceUrlByRamdon("SERVICE-LOG") + "doLog";
            OkHttpClient okHttpClient = new OkHttpClient();
            RequestBody body = new FormBody.Builder()
                    .add("user", SERVICE_ID)
                    .add("level", level)
                    .add("message", msg)
                    .build();
            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .build();
            Call call = okHttpClient.newCall(request);
            try {
                Response response = call.execute();
                return "true".equals( response.body().string() );
            } catch (IOException e) {
                e.printStackTrace();
            }
            return false;
        });
        new Thread(async).start();
        return async;
    }


    @Value("${spring.application.name}")
    @Autowired
    public void setServiceId(String id){
        SERVICE_ID = id;
    }


}
